from flask import jsonify
from flask_restful import Resource, fields, marshal_with, reqparse
from .models import *

# 类视图 CBV，视图函数 FBV
class HelloResource(Resource):
    def get(self):
        return jsonify({'meg':'get请求'})
    def post(self):
        return jsonify({'meg':'post请求'})

# 字段格式化
ret_fields = {
    'status': fields.Integer,
    'msg': fields.String,
    # 'data': fields.String
    'like':fields.String(default='ball'),
    'like2':fields.String(),
    'data2':fields.String(attribute='data') # 访问data的值
}

class UserResource(Resource):
    @marshal_with(ret_fields)
    def get(self):
        return {
            'status':1,
            'msg':'ok',
            'data':'千峰教育Python'
        }


user_fields = {
    'id':fields.Integer,
    'name':fields.String,
    'age':fields.Integer,
    'url':fields.Url(endpoint='id', absolute=True)
}
ret_fields2 = {
    'status': fields.Integer,
    'msg': fields.String,
    'data':fields.Nested(user_fields)
}

class User2Resource(Resource):
    @marshal_with(ret_fields2)
    def get(self):
        user = User.query.first()
        return {
            'status': 1,
            'msg': 'ok',
            'data': user
        }


user_fields2 = {
    # 'id':fields.Integer,
    'name':fields.String,
    'age':fields.Integer,
}
ret_fields3 = {
    'status': fields.Integer,
    'msg': fields.String,
    'data':fields.List(fields.Nested(user_fields2)),
}

class User3Resource(Resource):
    @marshal_with(ret_fields3)
    def get(self):
        users = User.query.all()
        return {
            'status': 1,
            'msg': 'ok',
            'data': users
        }

# 解析前端发送过来的数据
# 参数解析
parser = reqparse.RequestParser()
parser.add_argument('name', type=str, required=True, help='name是必须的参数')
parser.add_argument('age', type=int, action = 'append')
class User4Resource(Resource):
    def get(self):
        # 获取参数
        args = parser.parse_args()
        name = args.get('name')
        age = args.get('age')
        return {'name': name, 'age': age}


 # 字段格式化
ret_fields4 = {
     'status': fields.Integer,
     'msg': fields.String,
     'data':fields.String
 }

class User5Resource(Resource):
     @marshal_with(ret_fields4)
     def get(self):
         return {
             'status':1,
             'msg':'ok',
             'data':'千峰教育Python'
         }